import getShortcutByName from "./getShortcutByName";
import {decodeURIWrapper} from "../../util";

const fetchHighlights = async (name: string) => {
  const data = await getShortcutByName(name);
  if (!data.shortcut) {
    return;
  }
  const shortcut = data.shortcut;
  if (!shortcut.comments || shortcut.comments.trim() === "") return;
  const viewstates = shortcut.comments.trim().split("\n\n");
  let highlightAndComments = "";
  for (const viewstate of viewstates) {
    const [highlightId] = viewstate.split(";;").slice(0,1).map((item: string) => item.trim());
    if (viewstate.indexOf("*ver_image*") !== -1) {
      // TODO: Not implemented
    } else {
      const [highlightText] = viewstate.split(";;").slice(6,7).map((item: string) => decodeURIWrapper(item).trim());
      const [highlightComments] = viewstate.split(";;").slice(-1).map((item: string) => item.trim());
      const comments_decoded = decodeURIWrapper(highlightComments).replaceAll("\n", "\n > ");
      // @ts-ignore
      if (comments_decoded.trimEnd("\n") !== "") {
        // @ts-ignore
        highlightAndComments += `* [@](#${highlightId}) ${highlightText.trimEnd("\n")}\n> ${comments_decoded.trimEnd("\n")}\n`;
      } else {
        // @ts-ignore
        highlightAndComments += `* [@](#${highlightId}) ${highlightText.trimEnd("\n")}\n`;
      }
    }
  }
  highlightAndComments = highlightAndComments.replaceAll("\n\n", "\n").trim();
  return highlightAndComments;
}

export default fetchHighlights;
